package book.security;

import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.interfaces.DSAPrivateKey;
import java.util.Enumeration;
import org.junit.Test;

public class KeyPaireReader {
	public void read(String file, String passWord) throws Exception {
		FileInputStream fis = null;
		fis = new FileInputStream(new File(file));
		KeyStore keystore = KeyStore.getInstance("JKS");
		keystore.load(fis, passWord.toCharArray());
		System.out.println(keystore.containsAlias("mykey"));
		Enumeration<String> aliases = keystore.aliases();
		while (aliases.hasMoreElements()) {
			String alias = aliases.nextElement();
			String createDate = keystore.getCreationDate(alias).toLocaleString();
			System.out.println("createDate: " + createDate);
			Key key = keystore.getKey(alias, passWord.toCharArray());
			if (key != null && key instanceof PrivateKey) {
				if ("DSA".equals(key.getAlgorithm().toUpperCase())) {
					DSAPrivateKey pik = (DSAPrivateKey) key;
					System.out.println(pik.getX());
				}
			}
			Certificate[] certs = keystore.getCertificateChain(alias);
			for (Certificate cert : certs) {
				PublicKey puk = cert.getPublicKey();
				System.out.println(puk);
			}
		}
	}

	@Test
	public void test() throws Exception {
		read("D:\\keytooltest\\ca1.jks", "111111");
	}
}